package com.itheima;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessLock;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.junit.Before;

import java.util.concurrent.TimeUnit;

public class Ticket12306 implements Runnable {
    private int ticket = 10;
    private CuratorFramework client;
    private InterProcessMutex interProcessMutex;

   public Ticket12306(){
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000, 1);
        client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181").
                sessionTimeoutMs(60 * 1000).
                connectionTimeoutMs(15 * 1000).
                retryPolicy(retryPolicy).build();
        client.start();
        interProcessMutex=new InterProcessMutex(client,"/lock");
    }
    @Override
    public void run() {
        while (true) {
            //获取锁,这个是3秒钟的意思,就是说a获得了锁,b没有获得锁,那b就每隔3秒来获取一下锁
            try {
                interProcessMutex.acquire(3, TimeUnit.SECONDS);
                if (ticket > 0) {
                    System.out.println(Thread.currentThread() + "==" + ticket);
                    ticket--;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //释放锁
                try {
                    interProcessMutex.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
